package my.chat.controller;

import my.chat.Greeting;
import my.chat.common.pojo.LoginUser;
import my.chat.config.annotation.Login;
import my.chat.entity.ChatFriends;
import my.chat.entity.ChatMsg;
import my.chat.service.ChatFriendsService;
import my.chat.service.ChatMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Controller
public class ChatController {

	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;

	@Autowired
	private ChatFriendsService chatFriendsService;
	@Autowired
	private ChatMsgService chatMsgService;

	@MessageMapping("/all")
	@SendTo("/topic/greetings")
	public Greeting chatAll(ChatMsg message) {
		return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getMsg()) + "!");
	}

	@MessageMapping("/point")
	public void chatOne(ChatMsg message) {
	    chatMsgService.insertChatMsg(message);
		simpMessagingTemplate.convertAndSendToUser(message.getToUserId(), "topic", message);
	}

	/***
	 * 查询用户的好友
	 */
	@PostMapping("/chat/friends")
	@ResponseBody
	public List<ChatFriends> lkFriends(@Login LoginUser loginUser) {
		String userId = loginUser.getUserId();
		return chatFriendsService.lookUserAllFriends(userId);
	}

	/***
	 * 查询两个用户之间的聊天记录
	 */
	@PostMapping("/chat/msg/{receivedUserId}")
	@ResponseBody
	public List<ChatMsg> lkFriendsMsg(@Login LoginUser loginUser, @PathVariable("receivedUserId") String receivedUserId) {
		String userId = loginUser.getUserId();
		return chatMsgService.lookTwoUserMsg(new ChatMsg().setFormUserId(userId).setToUserId(receivedUserId));
	}
}
